<template>
  <div>
    <div class="def">
      <p style="text-align:center;font-size:24px;
      margin-bottom:18px;">地址信息</p>
      <div class="header" style="font-size:14px;">
        <button @click="addAddress" style="margin-right:10px;">添加收货地址</button>
        <Dialog ref="dialog"/>
        您当前存在{{addresses.length}}个收货地址,最多可创建10个
      </div>
      <div v-if="this.addresses.length !== 0">
        <div class="header" v-for="address in addresses" :key="address.address_id"> 
          <span>{{address.address_user}}</span>
          <span>{{address.address_tel}}</span>
          <span style="color:#c69c6c;" v-if="address.address_default == 1 ? true : false">默认地址</span>
          <span style="float:right;" @click="deleteAddress(address.address_id)"><i class="el-icon-delete"></i></span>
          <br/><span style="font-size:14px;">{{address.address_info}}</span>
          <span class="span">编辑</span>
          <span @click="defaultAddress(address.address_id)" class="span" v-if="address.address_default == 1 ? false : true">设为默认</span>
        </div>
      </div>
      <div v-if="this.addresses.length === 0">
        <el-empty description="地址为空，请添加地址！">
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script>
import {reqAddressPerson,reqAddressDelete,reqAddressDefault} from '../../api'
import Dialog from '../common/Dialog.vue'
export default {
    name:'Address',
    data() {
      return {
        addresses:[],
      }
    },
    components:{Dialog},
    methods: {
      addAddress(){ 
        this.$refs.dialog.open()
      },
      async deleteAddress(id){ //删除地址
        await reqAddressDelete(id)
        this.$message.success('地址删除成功！')
        if(this.$local.isExist('key')){
          this.addresses = await reqAddressPerson(this.$local.get('key'))
        }else{
          this.$message.error('登录令牌不存在！')
          this.$router.push('/user/info')
        }
      },
      async defaultAddress(id){
        await reqAddressDefault(id)
        if(this.$local.isExist('key')){
          this.addresses = await reqAddressPerson(this.$local.get('key'))
        }else{
          this.$message.error('登录令牌不存在！')
          this.$router.push('/user/info')
        }
      },
    },
    async mounted() {
      this.addresses = await reqAddressPerson(this.$local.get('key'))
      this.$bus.$on('updateAddress',(getData)=>{
        this.addresses = getData
      })
    },
    beforeDestroy() {
      this.$bus.$off('updateAddress')
    },
}
</script>

<style scoped>
  .def{
    margin-top: 30px;
    padding:0 16px 0 16px;
  }
  .header{
    border-radius: 5px;
    background:white;
    padding: 12px 10px;
    margin-bottom: 10px;
  }
  .header span{
    margin-right: 10px;
  }
  .span{
    font-size: 14px;
    float: right;
    color: #c69c6c;
    cursor: pointer;
  }
  span i:hover{
    color:#E64347;
  }
</style>